#pragma once
#include"index.hpp"
#include"tool.hpp"
#include<jsoncpp/json/json.h>
namespace searcher{
    class Searcher{
        public:
        Searcher(){}
        ~Searcher(){}
        private:
        myindex::Index*idex;
        public:
        void InitSearcher(const std::string&input)
        {
            //1. 获取或者创建index对象
            idex=new myindex::Index();
            //2. 根据index对象建立索引
            idex->Buildindex(input);
        }
        //query::搜索关键字
        //result::返回的结果
        void search(const std::string&query,std::string &result)
        {
            //1.分词
            std::vector<std::string> word;
            tool::JiebaUtil::CutString(query,&word);
            //2.查找
            std::vector<myindex::InvertedElem> inver_list;
            for(auto w:word)
            {
                boost::to_lower(w);
                myindex::InvertedList* list=idex->Getlist(w);
                inver_list.insert(inver_list.end(),list->begin(),list->end());

            }
            //3.排序(按照weight排)
            std::sort(inver_list.begin(),inver_list.end(),
                [](const myindex::InvertedElem &e1, const myindex::InvertedElem &e2){
                    return e1.weight>e2.weight;
                });
            //4.构建结果
            Json::Value root;
            for(auto &item:inver_list)
            {
                myindex::DocInfo*doc=idex->Getindex(item.id);
                Json::Value elem;
                elem["title"]=doc->title;
                elem["desc"]=GetDesc(doc->content,item.word);
                elem["url"]=doc->url;
                elem["id"]=item.id;
                elem["weight"]=item.weight;
                root.append(elem);
            }
            Json::FastWriter writer;
            result = writer.write(root);
        }
        std::string GetDesc(const std::string &html_content, const std::string &word)
        {
            //找到word在html_content中的首次出现，然后往前找50字节(如果没有，从begin开始)，往后找100字节(如果没有，到end就可以的)
            //截取出这部分内容
            const int prev_step = 50;
            const int next_step = 100;
            //1. 找到首次出现
            auto iter = std::search(html_content.begin(), html_content.end(), word.begin(), word.end(), [](int x, int y){
                    return (std::tolower(x) == std::tolower(y));
                    });
            if(iter == html_content.end()){
                return "None1";
            }
            int pos = std::distance(html_content.begin(), iter);

            //2. 获取start，end , std::size_t 无符号整数
            int start = 0; 
            int end = html_content.size() - 1;
            //如果之前有50+字符，就更新开始位置
            if(pos > start + prev_step) start = pos - prev_step;
            if(pos < end - next_step) end = pos + next_step;

            //3. 截取子串,return
            if(start >= end) return "None2";
            std::string desc = html_content.substr(start, end - start);
            desc += "...";
            return desc;
        }
    };
}